<template>
  <a-modal
    :open="props.modelVisible"
    title="分配详情"
    :width="'850px'"
    @cancel="emit('update:modelVisible', false)"
  >
    <template #footer>
      <a-popconfirm
        placement="left"
        :title="'是否要删除?'"
        ok-text="删除"
        cancel-text="取消"
        @confirm="deleteAssignment"
      >
        <a-button v-if="permission" type="primary" danger>删除</a-button>
      </a-popconfirm>
      <a-button @click="updateAssignmentEndTimeAndMember">确认</a-button>
    </template>
    <a-descriptions bordered>
      <a-descriptions-item label="分配状态" :span="1">
        <a-badge v-if="new Date() > props.assignment?.endTime" status="error" text="超时" />
        <a-divider v-if="new Date() > props.assignment?.endTime" type="vertical"></a-divider>
        <a-badge v-if="props.assignment?.assignmentStatus == 0" status="default" text="待领取" />
        <a-badge
          v-else-if="props.assignment?.assignmentStatus == 1"
          status="Processing"
          text="进行中"
        />
        <a-badge
          v-else-if="props.assignment?.assignmentStatus == 2"
          status="warning"
          text="待验收"
        />
        <a-badge
          v-else-if="props.assignment?.assignmentStatus == 3"
          status="Success"
          text="已完成"
        />
      </a-descriptions-item>
      <a-descriptions-item label="截至时间" :span="2">
        <a-date-picker
          v-model:value="selectedEndTime"
          style="width: 100%"
          :disabled="!permission"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          :allowClear="false"
        />
      </a-descriptions-item>

      <a-descriptions-item label="任务名称" :span="3">
        <div style="padding: 4px 11px">
          {{ props.assignment?.taskName }}
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="任务描述" :span="3">
        <div style="padding: 4px 11px">
          {{ props.assignment?.taskDescription }}
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="所属小组" :span="1">
        <div style="padding: 4px 11px">
          {{ props.assignment?.teamName }}
        </div>
      </a-descriptions-item>
      
      <a-descriptions-item label="领取时间" :span="1">
        <div style="padding: 4px 11px">
          {{
            props.assignment?.startTime
              ? dayjs(props.assignment?.startTime).format('YYYY-MM-DD HH:mm:ss')
              : ''
          }}
        </div>
      </a-descriptions-item>
      <a-descriptions-item label="完成时间" :span="2">
        <div style="padding: 4px 11px">
          {{
            props.assignment?.finishTime
              ? dayjs(props.assignment?.finishTime).format('YYYY-MM-DD HH:mm:ss')
              : ''
          }}
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="承担人员" :span="2">
        <a-select
          v-model:value="selectedUserIds"
          mode="multiple"
          placeholder="请选择承担对象"
          :showSearch="true"
          optionFilterProp="label"
          :disabled="!permission"
          :field-names="{ value: 'userId', label: 'userName' }"
          :options="items"
          style="width: 100%"
          :listHeight="180"
          :maxTagCount="3"
          :maxTagTextLength="5"
        >
          <template #tagRender="{ label, onClose, value }">
            <a-tag
              closable
              @close="onClose"
              style="margin-right: 3px"
            >
              {{ label }}
            </a-tag>
          </template>
        </a-select>
        <div v-if="selectedUserIds && selectedUserIds.length > 0" style="color: #52c41a; margin-top: 4px;">
          已选择 {{ selectedUserIds.length }} 名学生
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="创建人" :span="1">
        <div style="padding: 4px 11px">
          {{ props.assignment?.creatorName }}
        </div>
      </a-descriptions-item>
      <a-descriptions-item label="创建时间" :span="2">
        <div style="padding: 4px 11px">
          {{ dayjs(props.assignment?.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </div>
      </a-descriptions-item>
      
      <a-descriptions-item label="附件" :span="3">
        <div style="padding: 4px 11px; min-height: 100px;">
          <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
            <div style="font-size: 14px; color: rgba(0, 0, 0, 0.85);">任务相关附件</div>
            <a-upload
              v-if="permission"
              v-model:file-list="fileList"
              :customRequest="uploadAttachment"
              multiple
              :showUploadList="false"
              name="file"
            >
              <a-button type="primary" size="small">
                <upload-outlined></upload-outlined>
                上传附件
              </a-button>
            </a-upload>
          </div>
          <a-list item-layout="horizontal" :data-source="attachmentData">
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <download-outlined 
                    class="attachment-down-icon"
                    @click="downloadAttachment(item)"
                  />
                  <a-popconfirm
                    v-if="permission"
                    :title="'是否要删除' + item.attachmentName + '?'"
                    ok-text="删除"
                    cancel-text="取消"
                    @confirm="deleteAttachment(item)"
                  >
                    <delete-outlined class="attachment-delete-icon" />
                  </a-popconfirm>
                </template>
                <a-list-item-meta
                  style="cursor: pointer"
                  :description="`${formatBytes(item.size)} 来自 ${item.creatorName} | ${dayjs(
                    item.createTime
                  ).format('YYYY-MM-DD HH:mm:ss')}`"
                >
                  <template #title>
                    <a>{{ item.attachmentName }}</a>
                  </template>
                  <template #avatar>
                    <file-icon :fileName="item.attachmentName" size="36px" />
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
            <template #empty>
              <div style="text-align: center; color: rgba(0, 0, 0, 0.45);">
                暂无附件
              </div>
            </template>
          </a-list>
        </div>
      </a-descriptions-item>
    </a-descriptions>
  </a-modal>
</template>
<script lang="ts" setup>
import ProjectDao from '@/daos/project_dao';
import TaskDao from '@/daos/task_dao';
import AttachmentDao from '@/daos/attachment_dao';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { 
  UploadOutlined, 
  DownloadOutlined, 
  DeleteOutlined 
} from '@ant-design/icons-vue';
import FileIcon from '@/components/File/FileIcon.vue';

const store = useStore();
const projectDao = new ProjectDao();
const taskDao = new TaskDao();
const attachmentDao = new AttachmentDao();
//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  assignment: {
    type: Object
  }
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);
//截至时间
const selectedEndTime = ref();

//选中的小组id
const selectedTeamId = ref();
//选中的用户Id列表
const selectedUserIds = ref([]);
//项目ID
const projectId = store.getters.projectId;
//删除开放开关
const permission = ref<boolean>(false);
//检查是否开放部分按钮权限
const setPermission = (type) => {
  if (type == 0) {
    permission.value = true;
  } else {
    permission.value = false;
  }
};

//全部的小组成员列表
const teamItems = ref([]);
//根据选中的小组id 获取对应的成员
const changeMembers = async (teamId) => {
  try {
    const response = await projectDao.getStudentsByTeamId(teamId);
    const data = response.data.data;
    items.value = data;
    // 如果没有学生，显示提示
    if (data.length === 0) {
      hasMembers.value = false;
    } else {
      hasMembers.value = true;
    }
  } catch (error) {
    console.error('获取小组成员失败', error);
  }
};

//获取全部项目成员
const items = ref([]);
const hasMembers = ref(true);

//文件上传相关
const fileList = ref([]);
const attachmentData = ref([]);

// 获取附件列表
const findAttachments = async () => {
  if (props.assignment && props.assignment.taskId) {
    try {
      const result = await attachmentDao.findAttachmentsByTaskId(props.assignment.taskId);
      attachmentData.value = result.data.data;
    } catch (error) {
      console.error('获取附件列表失败', error);
    }
  }
};

// 上传附件
const uploadAttachment = async (file) => {
  try {
    const result = await attachmentDao.upLoadTaskAttachment(
      file.file,
      props.assignment.taskId,
      store.getters.userId
    );
    message.success('上传成功');
    findAttachments();
  } catch (error) {
    message.error('上传失败');
    console.error('上传附件失败', error);
  }
};

// 删除附件
const deleteAttachment = async (item) => {
  try {
    message.loading({ content: '正在删除...', key: 'deleting' });
    const result = await attachmentDao.deleteAttachmentByAttachmentId(
      item.attachmentId,
      item.attachmentUrl
    );
    
    if (result.data && result.data.code === 200) {
      // 从界面上移除该附件
      attachmentData.value = attachmentData.value.filter(
        (attachment) => attachment.attachmentId !== item.attachmentId
      );
      message.success({ content: '删除成功', key: 'deleting' });
    } else {
      // 删除失败，但可能数据库已删除，刷新列表
      message.error({ content: result.data?.msg || '删除失败', key: 'deleting' });
      findAttachments(); // 重新加载附件列表
    }
  } catch (error) {
    console.error('删除附件失败', error);
    message.error({ content: '删除失败: ' + (error.message || '未知错误'), key: 'deleting' });
    // 尝试刷新列表
    findAttachments();
  }
};

// 下载附件
const downloadAttachment = (item) => {
  // 创建下载链接
  const link = document.createElement('a');
  link.href = item.attachmentUrl;
  link.download = item.attachmentName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 格式化文件大小
const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};

//根据提交的时间更新数据
const updateAssignmentEndTimeAndMember = async () => {
  try {
    if (selectedEndTime.value) {
      const endTime = dayjs(selectedEndTime.value).format('YYYY-MM-DD HH:mm:ss');
      const result = await taskDao.updateAssignmentEndTimeAndMember(
        props.assignment.assignmentId,
        endTime,
        selectedTeamId.value,
        JSON.stringify(selectedUserIds.value)
      );
      if (result.data.code == 200) {
        message.success(result.data.msg);
        emit('confirm');
        emit('update:modelVisible', false);
      } else {
        message.warning(result.data.msg);
      }
    }
  } catch (error) {
    console.error('更新失败', error);
  }
};

//根据提交的时间删除数据
const deleteAssignment = async () => {
  try {
    const result = await taskDao.deleteAssignmentByAssignmentId([props.assignment.assignmentId]);
    if (result.data.code == 200) {
      message.success(result.data.msg);
      emit('confirm');
      emit('update:modelVisible', false);
    } else {
      message.warning(result.data.msg);
    }
  } catch (error) {
    console.error('删除失败', error);
  }
};

//初始化参数
const initData = () => {
  selectedTeamId.value = props.assignment?.teamId;
  selectedEndTime.value = dayjs(props.assignment?.endTime);
  selectedUserIds.value = props.assignment?.undertakers || [];
  //获取小组学生
  if (props.assignment?.teamId) {
    changeMembers(props.assignment.teamId);
  }
  //获取附件列表
  findAttachments();
  //根据当前用户判断是否有创建权限
  const userId = store.getters.userId;
  if (
    props.assignment?.creatorId == userId ||
    userId == props.assignment?.managerId
  ) {
    setPermission(0);
  } else {
    setPermission(1);
  }
};

//监听参数变化
watch(
  () => props.modelVisible,
  (val) => {
    if (val) {
      initData();
    }
  }
);

//页面加载
onMounted(() => {
  if (props.modelVisible) {
    initData();
  }
});
</script>
<style scoped>
.attachment-down-icon {
  color: #1890ff;
  font-size: 16px;
  cursor: pointer;
}
.attachment-delete-icon {
  color: #ff4d4f;
  font-size: 16px;
  cursor: pointer;
}
</style>
